package com.xgf.demo;

import com.xgf.demo.authorization.TokenManager;
import com.xgf.demo.authorization.config.Constants;
import com.xgf.demo.authorization.model.TokenModel;
import com.xgf.demo.entity.User;
import com.xgf.demo.exception.UnloginException;
import com.xgf.demo.repository.UserRespository;
import com.xgf.demo.util.LocalDateTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.UUID;

public class DbTokenmanager implements TokenManager {
    @Autowired
    private UserRespository userRespository;

    @Override
    public TokenModel createToken(long userId) {
        return null;
    }

    public TokenModel createToken(User user) {
        //使用uuid作为源token
        String token = UUID.randomUUID().toString().replace("-", "");
        user.setToken(token);
        LocalDateTimeUtil  localDateTimeUtil= LocalDateTimeUtil.getInstance();
        user.setTokenTime(localDateTimeUtil.LocaldateTimeToDate(localDateTimeUtil.plus(Constants.TOKEN_EXPIRES_HOUR, ChronoUnit.HOURS)));
        userRespository.save(user);
        TokenModel model = new TokenModel(user.getId(), token);
        return model;
    }

    public TokenModel getToken(String authentication) {
        if (authentication == null || authentication.length() == 0) {
            return null;
        }
        String[] param = authentication.split("_");
        if (param.length != 2) {
            return null;
        }
        //使用userId和源token简单拼接成的token，可以增加加密措施
        long userId = Long.parseLong(param[0]);
        String token = param[1];
        return new TokenModel(userId, token);
    }

    public boolean checkToken(TokenModel model) {
        if (model == null) {
            return false;
        }
        User user = userRespository.findByToken(model.getToken());
        if (user == null || !user.getToken().equals(model.getToken())) {
            return false;
        }
        //判断存在时间是否有效
        Date DbtokenTime =  user.getTokenTime();
        if(DbtokenTime == null){
            return false;
        }
        LocalDateTimeUtil  localDateTimeUtil= LocalDateTimeUtil.getInstance();
        boolean  isExties = localDateTimeUtil.isBofore(localDateTimeUtil.DateToLocalDateTime(DbtokenTime));
        //如果验证成功，说明此用户进行了一次有效操作，延长token的过期时间
        //update user set token = #{token}, token_time = #{token_time} where username = #{username}
        if(isExties){
            user.setToken(model.getToken());
            user.setTokenTime(getDate());
            user = userRespository.save(user);
        }else{
            new UnloginException("登录超时，请重新登录");
        }
        return isExties;
    }

    /**
     * 获得之后的token过期时间
     * @return
     */
    private Date getDate(){
        LocalDateTimeUtil  localDateTimeUtil= LocalDateTimeUtil.getInstance();
        return localDateTimeUtil.LocaldateTimeToDate(localDateTimeUtil.plus(Constants.TOKEN_EXPIRES_HOUR, ChronoUnit.HOURS));
    }

    public void deleteToken(long userId) {
        User user = userRespository.findOne(userId);
        user.setToken(null);
        user.setTokenTime(null);
        userRespository.save(user);
    }
}
